const createOffer = document.querySelector('button#createOffer');
console.log('createOffer:',createOffer);
createOffer.onclick = test;

const pc = new RTCPeerConnection();
const pc2 = new RTCPeerConnection();

function test(){
  if(!pc){
    console.error('pc is null!');
  }

  getStream();

  return;
}

function getStream(){
  const constraints = {
    audio: false,
    video: true
  }

  navigator.mediaDevices.getUserMedia(constraints)
    .then(getMediaStream)
    .catch(handleError)
}

function handleError(err){
  console.error('Failed to get Media Stream: ', err);
}

function getMediaStream(stream){
  stream.getTracks().forEach(track => {
    pc.addTrack(track);
  });


  const options = {
    offerToReceiveAudio: false,
    offerToReceiveVideo: true,
    iceRestart: true
  }

  pc.createOffer(options)
    .then(getOffer)
    .catch(handleError);
}

function getOffer(desc){
  console.log('getOffer desc.sdp:',desc.sdp);

  pc.setLocalDescription(desc);

  pc2.setRemoteDescription(desc);
  pc2.createAnswer()
    .then(getAnswer)
    .catch(handleError)
}

function getAnswer(desc){
  console.log('getAnswer desc.sdp:',desc.sdp);

  pc2.setLocalDescription(desc);

  pc.setRemoteDescription(desc);
}
